##################
# CreateSurveyWardMaps.R
# This file creates all ward map files used in the treatment messages
# It allows for the replication of example maps included in the main text and SI.
# Before running this code, you must update the working_dir variable below. 
# You must also provide a valid google mapping API key in the google_api_key variable below. 
# See ggmap::register_google() for details.
# Contact Ryan Jablonski, r.s.jablonski@lse.ac.uk with questions

# Log:
# Created by Inbok Rhee (project RA)
# Created Oct 23, 2016
# Updates Feb 12, 2017
# Edited for APSR replication 17 August 2023 by Ryan Jablonski
##################


# 0. preamble -------------------------------------------------------------
rm(list=ls())

# SETUP VARIABLES. EDIT AS NEEDED
working_dir="./APSR Replication/Generate Survey Maps"
google_api_key="XXX"

#using groundhog package to ensure consistent versioning
library(groundhog)
library(rgdal)
groundhog.library(plyr,'2023-04-01')
groundhog.library(dplyr,'2023-04-01')
groundhog.library(raster,'2023-04-01')
groundhog.library(rgeos,'2023-04-01')
groundhog.library(ggplot2,'2023-04-01')
groundhog.library(ggmap,'2023-04-01')
groundhog.library(maptools,'2023-04-01')
groundhog.library(tools,'2023-04-01')
groundhog.library(RColorBrewer,'2023-04-01')
groundhog.library(knitr,'2023-04-01')
groundhog.library(BBmisc,'2023-04-01')
groundhog.library(stringr,'2023-04-01')
groundhog.library(stringi,'2023-04-01')
groundhog.library(tools,'2023-04-01')

ggmap::register_google(key=google_api_key)

setwd(working_dir)

#check if output folders exist
if(!dir.exists("maps")){
  dir.create("maps")
}

if(!dir.exists("./maps/ward")){
  dir.create("./maps/ward")
}


# random assignment function
ra <- function(N,m,seed){
  set.seed(seed)
  assign <- cbind(1:N, 1:N %in% sample(1:N,m))
  return(assign)
}

# function to add footnote in ggplot
makeFootnote <- function(footnoteText =
                           format(Sys.time(), "%d %b %Y"),
                         size = 1, color = grey(.5))
{
  require(grid)
  pushViewport(viewport())
  grid.text(label = footnoteText ,
            x = unit(1,"npc") - unit(2, "mm"),
            y = unit(2, "mm"),
            just = c("right", "bottom"),
            gp = gpar(cex = size, col = color))
  popViewport()
}


school_df <- read.csv(paste0(working_dir,"/LC School Information Template 02202017b.csv"),
                      stringsAsFactors = FALSE)
# some corrections to the names in the template file (e.g., due to bielections)
new_names <- readxl::read_excel(paste0(working_dir,"/Name_corrections.xlsx"),
                                sheet=2)
head(new_names)
colnames(new_names)[5:6] <- c("old_name", "new_name")

for (i in 1:nrow(new_names)){
  school_df$winner_name_local[school_df$ps_ward_id==new_names$ps_ward_id[i]] <- new_names$new_name[i]
}


  
# 1. data cleaning and merging --------------------------------------------------------------
# Example Maps


set.seed(1)
library(maptools)
library(raster)
library(ggmap)

ken_adm <- getData("GADM", country="KEN", level=2)
head(ken_adm)

kenya_w <- ken_adm[ken_adm$NAME_2==sample(ken_adm$NAME_2, 1),]


data <- fortify(kenya_w)

# get map for all constituency
# set minimum longitude
if (max(data$long)-min(data$long)>=0.15){
  lonmin <- min(data$long)
  lonmax <- max(data$long)
} else {
  lonmin <- mean(data$long) - 0.08
  lonmax <- mean(data$long) + 0.08
}

# set minimum longitude
if (max(data$lat)-min(data$lat)>=0.2){
  latmin <- min(data$lat)
  latmax <- max(data$lat)
} else {
  latmin <- mean(data$lat) - 0.1
  latmax <- mean(data$lat) + 0.1
}

tryCatch({
  m1 <- get_map(location = c(lonmin-0.3, latmin-0.3,
                             lonmax+0.3, latmax+0.3),
                source = "google", maptype="road", color="bw")
  
}, error=function(e){
  m1 <- get_map(location = c(lonmin-0.1, latmin-0.1,
                             lonmax+0.1, latmax+0.1),
                maptype = "roadmap",
                color='bw',
                zoom=10)
})


m1 <- sub("EFEFEF", "FFFFFF", m1)

sdf <- data.frame(cbind(c(36.9, 37.0, 37.15),
                        c(-1.08, -1.04, -1.18),
                        sample(c("LIMPOPO SCHOOL", "CONGO SCHOOL", "ZAMBEZI SCHOOL"), 3),
                        sample(c("blue", "orange", "red"), 3)))


colnames(sdf) <- c("school_longitude", "school_latitude", "school_name", "color")
sdf$school_latitude <- as.numeric(as.character(sdf$school_latitude))
sdf$school_longitude <- as.numeric(as.character(sdf$school_longitude))
sdf$school_name <- as.character(sdf$school_name)
sdf
sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"

sdf$info <- paste0(sdf$school_name, "\n\n",
                   "Uniforms are ", sdf$color, " at this school\n")

sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order



p1 <- ggmap(m1) + 
  geom_path(aes(x = long, y = lat, group = group), data = data,
            colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
  xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
  geom_point(data = sdf, # create black boundary around red circle
             aes(x = school_longitude, 
                 y = school_latitude),
             colour = "black",
             size = 8) +
  geom_point(data = sdf, # create a red circle around the letters
             aes(x = school_longitude, 
                 y = school_latitude),
             colour = "red",
             size = 6) +
  geom_point(data = sdf, # plot schools and mark with letters
             aes(x = school_longitude, 
                 y = school_latitude, 
                 shape = info),
             size = 4,
             colour = "white") + 
  scale_shape_manual(values = sdf$letter) + # assign letters to points
  labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
  theme_bw() +
  theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
        axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
        axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
        legend.key = element_rect(fill = "red", colour = "black"),
        #legend.key = element_blank(), # remove boxes around legend shapres
        legend.text=element_text(size=11)) + # bigger legend text size
  #ggtitle(map_label) + # give title
  guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters

setwd(paste0(working_dir,"./maps/"))


footnote <- paste("Map ", sample(1:1000,1), sep=" ")

# get map for all constituency
# set minimum longitude
if (max(data$long)-min(data$long)>=0.15){
  lonmin <- min(data$long)
  lonmax <- max(data$long)
} else {
  lonmin <- mean(data$long) - 0.08
  lonmax <- mean(data$long) + 0.08
}

# set minimum longitude
if (max(data$lat)-min(data$lat)>=0.2){
  latmin <- min(data$lat)
  latmax <- max(data$lat)
} else {
  latmin <- mean(data$lat) - 0.1
  latmax <- mean(data$lat) + 0.1
}

tryCatch({
  m1 <- get_map(location = c(lonmin-0.3, latmin-0.3,
                             lonmax+0.3, latmax+0.3),
                source = "google", maptype="road", color="bw")
  
}, error=function(e){
  m1 <- get_map(location = c(lonmin-0.1, latmin-0.1,
                             lonmax+0.1, latmax+0.1),
                maptype = "roadmap",
                color='bw',
                zoom=10)
})


# m1 <- get_map(location = "Kenya",
#               source = "google", maptype="road", color="bw")


m1 <- sub("EFEFEF", "FFFFFF", m1)

sdf <- data.frame(cbind(c(36.9, 37.0, 37.15),
                        c(-1.08, -1.04, -1.18),
                        sample(c("LIMPOPO SCHOOL", "CONGO SCHOOL", "ZAMBEZI SCHOOL"), 3),
                        sample(c("150", "250", "75"), 3)))

colnames(sdf) <- c("school_longitude", "school_latitude", "school_name", "color")
sdf$school_latitude <- as.numeric(as.character(sdf$school_latitude))
sdf$school_longitude <- as.numeric(as.character(sdf$school_longitude))
sdf$school_name <- as.character(sdf$school_name)
sdf
sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"

sdf$info <- paste0(sdf$school_name, "\n\n",
                   "There are ", sdf$color, " students per classroom \n")

sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order

#map_label <- paste("Schools in Your Constituency", sep="")

data <- fortify(kenya_w)

p2 <- ggmap(m1) + 
  geom_path(aes(x = long, y = lat, group = group), data = data,
            colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
  xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
  geom_point(data = sdf, # create black boundary around red circle
             aes(x = school_longitude, 
                 y = school_latitude),
             colour = "black",
             size = 8) +
  geom_point(data = sdf, # create a red circle around the letters
             aes(x = school_longitude, 
                 y = school_latitude),
             colour = "red",
             size = 6) +
  geom_point(data = sdf, # plot schools and mark with letters
             aes(x = school_longitude, 
                 y = school_latitude, 
                 shape = info),
             size = 4,
             colour = "white") + 
  scale_shape_manual(values = sdf$letter) + # assign letters to points
  labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
  theme_bw() +
  theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
        axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
        axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
        legend.key = element_rect(fill = "red", colour = "black"),
        #legend.key = element_blank(), # remove boxes around legend shapres
        legend.text=element_text(size=11)) + # bigger legend text size
  #ggtitle(map_label) + # give title
  guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters


setwd(paste0(working_dir,"./maps/"))

footnote <- paste("Map ", sample(1:1000,1), sep=" ")


# 2. Ward: Assign Treatment -----------------------------------------------

# Assign treatment status
total_school_req <- 12 # for now, one per ward/treatment

ward_sampling <- read.csv(paste0(working_dir,"/Ward_Sampling02202017.csv"),
                          stringsAsFactors = FALSE)

table(school_df$ps_ward_id)
table(ward_sampling$ps_ward_id)

unique(school_df$ps_ward_id[!(school_df$ps_ward_id %in% ward_sampling$ps_ward_id)])
unique(ward_sampling$ps_ward_id[!(ward_sampling$ps_ward_id %in% school_df$ps_ward_id)])

school <- left_join(ward_sampling, school_df, by="ps_ward_id")

school$ward <- tolower(school$ps_ward.x)

school$treatment <- 0 # create placeholder
school$selected <- 0 # create placeholder
school$map_h <- 0 

seed <- 123456789
set.seed(seed)

#school$ps_ward_id <- school$ps_ward_id.x

i <- 176
head(school$Map_Order)
school$Map_Order <- gsub(" ", "", school$Map_Order)
school$Map_Order <- gsub(",", " , ", school$Map_Order)

aaa <- school %>% group_by(ps_ward_id) %>% tally
aaa[order(aaa$n),]

aa <- unique(school$ps_ward_id[!is.na(school$ps_ward_id)])
aa <- aa[order(aa)]
aa
end <- length(aa)


i <- 1
# assign treatment
for (i in 1:end){
  if (nrow(school[which(school$ps_ward_id==aa[i]),]) >= total_school_req){
    # randomly select three schools each  
    selected <- ra(nrow(school[which(school$ps_ward_id==aa[i]),]), total_school_req, seed=seed)[,2]
    school$selected[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))] <- selected
    school$treatment[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))] <- selected
    map_list <- unlist(strsplit(school$Map_Order[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))][1], " , "))
    
    treated <- sample(rep(map_list[-1], 3), 12)

    school$treatment[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude) & school$selected==1)] <- treated
  }
  
  else if (nrow(school[which(school$ps_ward_id==aa[i]),]) < total_school_req &
           nrow(school[which(school$ps_ward_id==aa[i]),]) > 3){
    # randomly select three schools each
    per_treatment <- round_any(nrow(school[which(school$ps_ward_id==aa[i]),]), 3, floor)
    order <- c(unlist(strsplit(school$Map_Order[which(school$ps_ward_id==aa[i])][1], " , ")))[-1]
    order <- order[1:(per_treatment/3)]
    
    selected <- ra(nrow(school[which(school$ps_ward_id==aa[i]),]), per_treatment, seed=1000)[,2]
    school$selected[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))] <- selected
    school$treatment[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))] <- selected
    
    treated <- as.vector(sample(rep(order, 3), per_treatment))
    school$treatment[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude) & school$selected==1)] <- treated
    
    school$map_h[which(school$ps_ward_id==aa[i] & !is.na(school$school_longitude))] <- ra(nrow(school[which(school$ps_ward_id==aa[i]),]), 3, seed=100)[,2]
  }
}

# Extract councillor first and last name only
library(BBmisc)

school$councilor_name <- trimws(school$winner_percent_local)
library(stringr)
school$councilor_name1 <- paste(word(school$councilor_name, 1), word(school$councilor_name, -1), sep=" ")
school$councilor_name1 <- capitalizeStrings(school$councilor_name1, all.words = TRUE, lower.back = TRUE)

# School names into Uppercase
school$school_name <- trimws(school$school_name)
school$school_name <- toupper(school$school_name)


# Save
setwd(paste0(working_dir,"./maps/"))

filename <- paste(Sys.Date(), "local-randomized.csv", sep="")
write.csv(school, file=filename)



school[school$ps_ward_id==3,]
nrow(school[school$ps_ward_id==20,])

# 3. mapping: by ward -----------------------------------------------------
## Correct classromm variable

school$school_classrooms_total <- school$school_classrooms_permanent + school$school_classrooms_temporary

## Correct/create service type variable
end <- nrow(school)
school$project_types <- NA

for (i in 1:end){
  school$project_types[i] <- paste0(unique(c(school$project_type1[i], 
                                             school$project_type2[i], 
                                             school$project_type3[i], "\n",
                                             school$project_type4[i],
                                             school$project_type5[i])), collapse = ", ")
}

school$project_types <- gsub(", NA,", "", school$project_types)
school$project_types <- gsub(", NA$", "", school$project_types)
school$project_types <- gsub(", \n$", "", school$project_types)
school$project_types <- gsub(" \n$", "", school$project_types)
school$project_types <- gsub("NA", "", school$project_types)

school$project_types <- paste0("helping with ", school$project_types)
school$project_types <- gsub("helping with $", "", school$project_types)

school$project_types <- paste0(school$project_types, "\n")
library(stringi)
school$project_types <- stri_replace_last_fixed(school$project_types, ",", " and")
school$project_types <- gsub("^\n$", "", school$project_types)

unique(school$project_types)
school$past_aid_project[is.na(school$past_aid_project)] <- 0


# School needs
unique(school$school_needs)
school$school_needs[school$school_needs=="MUCH HIGHER NEEDS"] <- "MUCH HIGHER NEEDS THAN"
school$school_needs[school$school_needs=="HIGHER NEEDS"] <- "HIGHER NEEDS THAN"
school$school_needs[school$school_needs=="MUCH LOWER NEEDS"] <- "MUCH LOWER NEEDS THAN"
school$school_needs[school$school_needs=="LOWER NEEDS"] <- "LOWER NEEDS THAN"
school$school_needs[school$school_needs=="ABOUT THE SAME NEEDS"] <- "ABOUT THE SAME NEEDS AS"

### Get data (shapefile)
setwd(paste0(working_dir,"./shapefiles/Malawi_2014_Ward_Boundary/"))


malawi <- readShapeSpatial("Malawi_2014_Ward_Boundary.shp", proj4string=CRS("+init=epsg:32736"))
malawi <- spTransform(malawi, CRS("+init=epsg:4326"))


unique(school$WardName[school$ps_ward_id==438])
unique(school$constituency[school$ps_ward_id==415])

school$map_ward[grepl("juma", school$map_ward, ignore.case = TRUE)]


# Align Shp file with School data for mering with ids
school$ward <- tolower(trimws(school$map_ward))
school$constituency <- tolower(trimws(school$map_constituency))

ss <- school %>% dplyr::select(ps_district.x, ps_district.y, map_district.x, map_district.y, school_district,
                               ps_constituency, school_constituency, constituency,
                               ps_ward.x, ps_ward.y, ward, school_ward.x, school_ward.y,
                               ps_ward_id)

keep <- c("constituency", "ward", "ps_ward_id")
ss <- ss[keep]
ss$constituency <- tolower(trimws(ss$constituency))
ss$ward <- tolower(trimws(ss$ward))
ss <- ss[!duplicated(ss),]

colnames(malawi@data) <- c("distcode", "district", "label", "ward", "constituency")
malawi$district <- tolower(trimws(malawi$district))
malawi$ward <- tolower(trimws(malawi$ward))
malawi$constituency <- tolower(trimws(malawi$constituency))
dd <- malawi@data
keep <- c("ward", "constituency")
dd <- dd[keep]
sss <- anti_join(dd, ss)
sss <- sss[!duplicated(sss),]


# Constituency
ss$constituency[!(ss$constituency %in% dd$constituency)]
unique(dd$constituency[!(dd$constituency %in% ss$constituency)])
ss$constituency[grepl("nkhata", ss$constituency)]
dd$constituency[grepl("mpenu", dd$constituency)]

# Ward
ss$ward[!(ss$ward %in% dd$ward)]

aa <- ss$ward[!(ss$ward %in% dd$ward)]
aa[order(aa)]

school <- school[school$ps_ward_id!=185,]
# 228, 320
school <- school[!is.na(school$Map_Order),]

ss <- school %>% dplyr::select(constituency, ward, ps_ward_id)
ss <- ss[!duplicated(ss),]
unique(ss$ps_ward_id)

dd <- dd[!duplicated(dd),]

ss$constituency[!(ss$constituency %in% dd$constituency)]
ss$ward[!(ss$ward %in% dd$ward)]

unique(dd$constituency[!(dd$constituency %in% ss$constituency)])
unique(dd$ward[!(dd$ward %in% ss$ward)])

unique(ss$constituency[grepl("mpenu", ss$constituency)])
unique(ss$ward[grepl("nde", ss$ward)])

school$Map_Order <- gsub(" ", "", school$Map_Order)
school$Map_Order <- gsub(",", " , ", school$Map_Order)

malawi@data <- left_join(malawi@data, ss)


aa <- unique(school$ps_ward_id)
aa <- aa[order(aa)]
head(aa)

#start <- 352
#end <- 3


start <- 221
end <- length(unique(school$ps_ward_id))

i <- 3

i


for (i in start:end){
  print(paste0(i, "/", end))

    malawi_w <- malawi[which(malawi$ps_ward_id == aa[i]),]
    data <- fortify(malawi_w)
    
  if(nrow(data)!=0){

    
    # get map for all wards
    # set minimum longitude
    if (max(data$long)-min(data$long)>=0.15){
      lonmin <- min(data$long)
      lonmax <- max(data$long)
    } else {
      lonmin <- mean(data$long) - 0.08
      lonmax <- mean(data$long) + 0.08
    }
    
    # set minimum longitude
    if (max(data$lat)-min(data$lat)>=0.2){
      latmin <- min(data$lat)
      latmax <- max(data$lat)
    } else {
      latmin <- mean(data$lat) - 0.1
      latmax <- mean(data$lat) + 0.1
    }
    
    tryCatch({
      m1 <- get_map(location = c(lonmin-0.1, latmin-0.1,
                                 lonmax+0.1, latmax+0.1), 
                    source = "google", maptype="road", color="bw")
      
    }, error=function(e){
      m1 <- get_map(location = c(lonmin-0.1, latmin-0.1,
                                 lonmax+0.1, latmax+0.1), 
                    maptype = "roadmap",
                    color='bw',
                    zoom=10)
    })
    
    
    m1 <- sub("EFEFEF", "FFFFFF", m1)
    ward_sampling[ward_sampling$ps_ward_id==252,]

    sdfAll <- as.data.frame(school[which(school$ps_ward_id==aa[i]),]) # subset for the ward
    rownames(sdfAll) <- 1:nrow(sdfAll)
    
    # 3.0. Example Map
    map_folder <- "Ward_TestMap"
    if(strsplit(sdfAll$Map_Order[1], " , ")[[1]][1]=="A"){
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))

      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p1)
      makeFootnote(footnote, color = "black")
      dev.off()
    } else if(strsplit(sdfAll$Map_Order[1], " , ")[[1]][1]=="B"){
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p2)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.1. Map C --------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "C"),]
    
    if (nrow(sdf)>0 & "C" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      sdf$info <- paste0("\n", sdf$school_name, "\n")
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="C")
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.2. Map D --------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "D"),]
    
    if (nrow(sdf)>0 & "D" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of",
                         " people in this community voted for ", sdf$winner_name_local, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="D")
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    
    
    # 3.3. Map E --------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "E"),]
    
    if (nrow(sdf)>0 & "E" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most in this ward because \n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", 
                         sdf$school_classrooms_total, " classrooms are temporary \n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="E")
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    # 3.4. Map F --------------------------------------------------------------
    
    
    sdf <- sdfAll[which(sdfAll$treatment== "F"),]
    
    if (nrow(sdf)>0 & "F" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="F")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most because \n",
                         " - Tearfund’s audits show classroom quality is ", sdf$tearfund_audit, "\n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", sdf$school_classrooms_total, 
                         " classrooms are temporary \n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.5. Map G --------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "G"),]
    
    if (nrow(sdf)>0 & "G" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="G")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      }else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.6.  Map F -------------------------------------------------------------
    
    # Map H
    sdf <- sdfAll[which(sdfAll$treatment== "H" | sdfAll$map_h==1),]
    
    if (nrow(sdf)>0 & "H" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="H")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
        map_folder <- "Ward_KnowledgeMap"
        
        mainDir <- paste0(working_dir, "./maps/ward")
        subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    sdf <- sdfAll[which(sdfAll$map_h== 1),]
    
    if (nrow(sdf)>0 & "H" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="H")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      map_folder <- "Ward_KnowledgeMap"
      
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.7. Map I --------------------------------------------------------------
    
    # Map I
    sdf <- sdfAll[which(sdfAll$treatment== "I"),]
    
    if (nrow(sdf)>0 & "I" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="I")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of", " people in this community",
                         " voted for ", sdf$winner_name_local, "\n\n",
                         " This school has ", sdf$school_needs, " most in this ward because \n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits=0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits=0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits=0), " out of ", 
                         round(sdf$school_classrooms_total, digits=0), " classrooms are temporary\n")
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    
    # 3.8. Map J --------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "J"),]
    
    if (nrow(sdf)>0 & "J" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="J")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of",  
                         " people in this community",
                         " voted for ", sdf$winner_name_local, "\n\n",
                         " This school has ", sdf$school_needs, " most because \n",
                         " - Tearfund’s audits show classroom quality is ", sdf$tearfund_audit, " \n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits=0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits=0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits=0), " out of ", 
                         round(sdf$school_classrooms_total, digits=0), " classrooms are temporary\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.9. Map K --------------------------------------------------------------
    
    
    sdf <- sdfAll[which(sdfAll$treatment== "K"),]
    
    if (nrow(sdf)>0 & "K" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="K")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of", 
                         " people in this community",
                         " voted for ", sdf$winner_name_local, "\n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types, "\n")
      
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.10. Map L -------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "L"),]
    
    if (nrow(sdf)>0 & "L" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="L")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most in this ward because \n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", sdf$school_classrooms_total, " classrooms are temporary \n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.11. Map M -------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "M"),]
    
    if (nrow(sdf)>0 & "M" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="M")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most because \n",
                         " - Tearfund’s audits show classroom quality is ", sdf$tearfund_audit, "\n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", sdf$school_classrooms_total, 
                         " classrooms are temporary \n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    # 3.11. Map N -------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "N"),]
    
    if (nrow(sdf)>0 & "N" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="N")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most because \n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", sdf$school_classrooms_total, 
                         " classrooms are temporary \n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of", " people in this community",
                         " voted for ", sdf$winner_name_local, "\n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types)
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
    
    
    
    # 3.11. Map N -------------------------------------------------------------
    
    sdf <- sdfAll[which(sdfAll$treatment== "O"),]
    
    if (nrow(sdf)>0 & "O" %in% unlist(strsplit(sdf$Map_Order[1], " , "))){
      sdf <- sdf[order(sdf$school_longitude),] # sort by latitude and longitude
      sdf$id <- LETTERS[1:nrow(sdf)] # assign letters
      sdf$letter <- unlist(lapply(sdf$id, utf8ToInt))  # convert from letters to UTF-8 encoded "shapes"
      
      order_position <- which(unlist(strsplit(sdf$Map_Order[1], " , "))=="O")
      
      sdf$info <- paste0("\n", sdf$school_name, "\n\n",
                         " This school has ", sdf$school_needs, " most because \n",
                         " - Tearfund’s audits show classroom quality is ", sdf$tearfund_audit, "\n",
                         " - There are ", round(sdf$student_to_classroom_ratio, digits = 0), " students in each classroom \n",
                         " - There are ", round(sdf$student_to_teacher_ratio, digits = 0), " student per teacher \n",
                         " - ", round(sdf$school_classrooms_temporary, digits = 0), " out of ", sdf$school_classrooms_total, 
                         " classrooms are temporary \n\n",
                         " ", round(sdf$winner_percent_local*100, digits=0), "% of", " people in this community",
                         " voted for ", sdf$winner_name_local, "\n\n",
                         " Donors have ", sdf$past_aid_project, " project(s) at this school \n",
                         " ",sdf$project_types, "\n")
      
      sdf$info <- factor(sdf$info, levels = sdf$info[order(sdf$id)], ordered = TRUE) # align order
      
      
      # map title
      map_label <- paste("Schools in Your Ward", sep="")
      
      p <- ggmap(m1) + 
        geom_path(aes(x = long, y = lat, group = group), data = data,
                  colour = 'grey30', size = 1, lineend = "butt", linejoin = "round", linemitre = 1) +
        xlim(min(data$long), max(data$long)) + ylim(min(data$lat), max(data$lat)) + coord_fixed() +
        geom_point(data = sdf, # create black boundary around red circle
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "black",
                   size = 8) +
        geom_point(data = sdf, # create a red circle around the letters
                   aes(x = school_longitude, 
                       y = school_latitude),
                   colour = "red",
                   size = 6) +
        geom_point(data = sdf, # plot schools and mark with letters
                   aes(x = school_longitude, 
                       y = school_latitude, 
                       shape = info),
                   size = 4,
                   colour = "white") + 
        scale_shape_manual(values = sdf$letter) + # assign letters to points
        labs(shape="", x="", y="") + # remove x-axis, y-axis, and legend titles
        theme_bw() +
        theme(plot.title = element_text(vjust=1, hjust=0, size=18), # give enough space after title
              axis.ticks.y = element_blank(),axis.text.y = element_blank(), # suppress y-axis ticks and label
              axis.ticks.x = element_blank(),axis.text.x = element_blank(), # suppress x-axis ticks and label
              legend.key = element_rect(fill = "red", colour = "black"),
              #legend.key = element_blank(), # remove boxes around legend shapres
              legend.text=element_text(size=11)) + # bigger legend text size
        ggtitle(map_label) + # give title
        guides(shape=guide_legend(ncol=1, override.aes=list(size=5))) # increased size for letters
      
      if (order_position == 2){
        map_folder <- "Map_Two"
      } else if (order_position == 3){
        map_folder <- "Map_Three"
      } else if (order_position == 4){
        map_folder <- "Map_Four"
      } else if (order_position == 5){
        map_folder <- "Ward_KnowledgeMap"
      } 
      mainDir <- paste0(working_dir, "./maps/ward")
      subDir <- paste0(gsub("/", "_", aa[i]))
      dir.create(file.path(mainDir, subDir), showWarnings = F)
      setwd(file.path(mainDir, subDir))
      
      footnote <- paste(map_folder, sdf$ward_id.x[1], sep=" ")
      
      # save with ward name as file name
      file_name <- paste0(aa[i], "_", gsub(" ", "", gsub("/", "_", unique(school$ward[school$ps_ward_id==aa[i]]))), "_", map_folder, ".png")
      png(file_name, width = 11, height = 8.5, units='in', res=600)
      print(p)
      makeFootnote(footnote, color = "black")
      dev.off()
    }
    
  }
}
